<template>
  <view class="login-container">
    <uni-icons type="contact-filled" size="100" color="#afafaf"></uni-icons>
    <!-- open-type="getUserInfo @getuserinfo=" 登录固定写法 -->
    <button type="primary" open-type="getUserInfo" @getuserinfo="getuserinfo" class="btn-login">一键登录</button>
    <text class="tips-text">登录后尽享更多权益</text>
  </view>
</template>
<script>
  import {
    mapMutations,
    mapState
  } from 'vuex'
  export default {
    data() {
      return {}
    },
    computed: {
      ...mapState('m_user', ['redirectInfo'])
    },
    methods: {
      // 
      ...mapMutations('m_user', ['updateUserInfo', 'updateToken', 'updateRedirectInfo']),
      async getuserinfo(e) {
        console.log(e)
        if (e.detail.errMsg === 'getUserInfo:fail auth deny')
          return uni.$showMsg('取消了本地登录授权')
        this.updateUserInfo(e.detail.userInfo);
        this.getToken(e.detail)
      },
      async getToken(info) {
        // 获取code
        const [err, res] = await uni.login().catch(err => err)
        if (res?.errMsg !== 'login:ok') return uni.$showMsg('登录失败')
        console.log(res)
        console.log(info)
        const obj = {
          code: res.code,
          encryptedData: info.encryptedData,
          iv: info.iv,
          rawData: info.rawData,
          signature: info.signature
        }
        console.log(obj)
        // const {
        //   data: loginResult
        // } = await uni.$http.post('/api/public/v1/users/wxlogin', obj)
        // if (loginResult.meta.state !== 200) return uni.$showMsg('登录失败')
        // uni.$showMsg('登录成功')

        // 存token
        const token =
          'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIzLCJpYXQiOjE1NjQ3MzAwNzksImV4cCI6MTAwMTU2NDczMDA3OH0.YPt-XeLnjV-_1ITaXGY2FhxmCe4NvXuRnRB8OMCfnPo'
        this.updateToken(token)
        this.navigateBack()
      },
      navigateBack() {
        if (this.redirectInfo?.openType === 'switchTab') {
          uni.switchTab({
            url: this.redirectInfo.from,
            complete: () => {
              this.updateRedirectInfo(null)
            }
          })
        }
      }
    }
  }
</script>
<style lang="scss">
  .login-container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 750rpx;

    .btn-login {
      width: 90%;
      border-radius: 15px;
      background-color: #c00000;
    }

    .tips-text {
      margin-top: 5px;
      color: gray;
      font-size: 12px;
    }
  }
</style>